<template>
  <div ref="wrapperContainer" class="wrapper-container" style="height: 100%; overflow: auto;">
    <div class="wrapper">
      <div class="thumbnail" v-for="image in images" :key="image.id">
        <img ref="skewElems" v-lazy="image.src" alt="" class="skewElem" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

const wrapperContainer = ref<HTMLElement | null>(null);
const skewElems = ref<HTMLImageElement[]>([]); // 存储所有 img 元素
// const images = Array.from({ length: 52 }, (_, i) => ({
//   id: i + 1,
//   src: `https://picsum.photos/600/600?random=${i + 1}`,
// }));

const images = Array.from({ length: 52 }, (_, i) => ({
  id: i + 1,
  src: `https://picsum.photos/600/${Math.floor(Math.random() * (800 - 300 + 1)) + 300}?random=${i + 1}`,
}));

gsap.registerPlugin(ScrollTrigger);

onMounted(() => {
  // 使用 setTimeout 延迟初始化，确保 DOM 已完全渲染
  setTimeout(() => {

    if (!wrapperContainer.value || skewElems.value.length === 0) return;

    let proxy = { skew: 0.1 };
    let clampedSkew = gsap.utils.clamp(-20, 20);
    // 使用 ref 获取的元素绑定 quickSetter
    let skewSetters = skewElems.value.map((el) => gsap.quickSetter(el, "skewY", "deg"));
    // 初始化 ScrollTrigger
    const trigger = ScrollTrigger.create({
      scroller: wrapperContainer.value,
      onUpdate: (self) => {
        let skew = clampedSkew(self.getVelocity() / -300);
        if (Math.abs(skew) > Math.abs(proxy.skew)) {
          proxy.skew = skew;
          gsap.to(proxy, {
            skew: 0,
            duration: 0.8,
            ease: "power3",
            overwrite: true,
            onUpdate: () => {
              skewSetters.forEach((setter) => setter(proxy.skew));
            },
          });
        }
      },
    });

    onUnmounted(() => {
      trigger.kill(); // 清理 ScrollTrigger
    });
  }, 10000); // 延迟 300ms 确保元素渲染完
});
</script>

<style lang="scss" scoped>
.wrapper {
  max-width: 100%;
  column-count: 3;
  column-gap: 20px;
  row-gap: 20px;
}

.thumbnail {
  width: 100%;
  opacity: 0.5;
  margin-bottom: 20px;
}

.thumbnail:hover {
  opacity: 1;
  transition: opacity 0.5s ease;
}

.thumbnail>img {
  width: 100%;
  height: auto;
  transform: skewY(0deg);
  object-fit: cover;
  /* 确保初始状态 */
}

@media (max-width: 768px) {
  .thumbnail {
    width: 50%;
  }
}

@media (max-width: 480px) {
  .thumbnail {
    width: 100%;
  }
}
</style>
